package org.elzat.healthboxgatewayapp.gateway;

import lombok.AllArgsConstructor;
import org.elzat.healthboxgatewayapp.config.HealthBoxGatewayConfig;
import org.elzat.healthboxgatewayapp.filter.HealthBoxGatewayAddRequestHeaderFilter;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.GatewayFilterSpec;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@AllArgsConstructor
public class HealthBoxGateWay {
    private final HealthBoxGatewayConfig routerConfig;

    @Bean
    RouteLocator routeLocator(RouteLocatorBuilder builder) {
        RouteLocatorBuilder.Builder routeBuilder = builder.routes();
        for (HealthBoxGatewayConfig.Routes r : routerConfig.getRoutes()) {
            if (r.getFrom() == null || r.getTo() == null || r.getDoFilter() == null)
                continue;
            if (r.getDoFilter())
                routeBuilder = routeBuilder
                        .route(routSpec -> routSpec
                                .path(r.getFrom())
                                .filters(this::commonFilterSpec)
                                .uri(r.getTo()));
            else routeBuilder = routeBuilder
                    .route(routSpec -> routSpec
                            .path(r.getFrom())
                            .uri(r.getTo()));
        }
        return routeBuilder.build();
    }

    @Bean
    GatewayFilter addRequestHeaderFilter() {
        return new HealthBoxGatewayAddRequestHeaderFilter();
    }
    private GatewayFilterSpec commonFilterSpec(GatewayFilterSpec spec) {
        spec.filter(addRequestHeaderFilter());
        return spec;
    }
}
